with Logging;

package body AC3_Analyzer is

   -- AC3 frames are 32ms in length, or 2880 ticks of the 90KHz clock.
   -- The resulting frame rate is 31.25 fps.
   procedure Read(Frame: out Byte_Buffer_Type; InFile : in IO.File_Type) is
      I : Positive := 2; -- so we can safely look back 1
      Current : IO.Byte_Type;
      use type Stream_IO.Positive_Count;
   begin
      -- init buffer
      Frame.Byte_Buffer(1) := 1;
      Frame.Start_Pos := 1;
      Frame.Size := 0;

      while (not Stream_IO.End_Of_File(InFile.File)) loop
         Byte_Type'Read(InFile.File_Access, Current);
         Frame.Byte_Buffer(I) := Current;

         if Frame.Byte_Buffer(I) = 16#77# and Frame.Byte_Buffer(I-1) = 16#0B# then
            if Frame.Start_Pos = 1 then
               Frame.Start_Pos := I-1;
            else
               Frame.Size := (I - 1) - Frame.Start_Pos;
               -- move back file pointer
               Stream_IO.Set_Index(InFile.File, Stream_IO.Index(InFile.File) - 2);
               Logging.Info("Found Frame length: " & Integer'Image( Frame.Size ));
               Logging.Info("File index: " & Stream_IO.Positive_Count'Image(Stream_IO.Index(InFile.File) ));
               return;
            end if;
         end if;
         I := I + 1;
      end loop;

      -- return the last nal
      if Frame.Start_Pos > 1 then
         Frame.Size := I - Frame.Start_Pos;
      end if;

   end Read;

end AC3_Analyzer;
